package com.example.capstome;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;

import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;


public class CommentActivity extends AppCompatActivity {
    private static Context appContext;

    private DB_Helper dbHelper;
    // 记录第一个评论所在数据集的位置
    private int cursor_index = 0;
    // 记录该视频的评论总数
    private int comment_num = 0;
    // 获取按点赞数排列的数据集的查询语句
    public static String  query_comment = "SELECT * FROM " + DB_Common_Contract.CommentEntry.TABLE_NAME +
            " ORDER BY " + DB_Common_Contract.CommentEntry.COLUMN_COMMENT_SUPPORT + " DESC;";;

    // 获取滑动窗口组件和最大可显示评论数
    private RecyclerView recyclerView;

    // 记录正在显示的每条评论再数据表里的id
    private static ArrayList<String> comment_id = new ArrayList<String>();
    // 评论适配器的数据
    ArrayList<Comment> data = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);

        setContentView(R.layout.activity_comment);
        dbHelper = new DB_Helper(this);
        //DB_Helper.addUser(new User("2", "andi","https://tse4-mm.cn.bing.net/th/id/OIP-C.4UybU_JIpdf8DKhxUT3GLwHaJ3?rs=1&pid=ImgDetMain"));

//评论区显示部分
       recyclerView = findViewById(R.id.rv_comment);
        // recyclerView.setLayoutManager(new LinearLayoutManager(this));    写布局文件里了

        //填充启动时初始内容
        CommentInit();
        // 初始化评论适配器
        RecyclerView rv = findViewById(R.id.rv_comment);
        CommentAdapter commentAdapter = new CommentAdapter(this,data);
        rv.setAdapter(commentAdapter);

        // 添加按键监视器
        addButtonClickListener();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    // 构造函数、getter和setter方法
    public CommentActivity() {

    }

    public DB_Helper getDbHelper(){
        return dbHelper;
    }

    public static String getComment_id(int index) {
        return comment_id.get(index);
    }

    //根据评论里的id找图片和用户名
    @SuppressLint("Range")
    private User GetUserDataFromID(String id){
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        String selection = DB_User_Contract.UserEntry._ID + "=" + id;
        String query = "SELECT * FROM " + DB_User_Contract.UserEntry.TABLE_NAME + " WHERE " + selection;
        Cursor cursor = dbHelper.QueryDB(query, db);
        cursor.moveToFirst();
        User user = new User(id, cursor.getString(cursor.getColumnIndex(DB_User_Contract.UserEntry.COLUMN_USER_NAME)), cursor.getString(cursor.getColumnIndex(DB_User_Contract.UserEntry.COLUMN_USER_ImgURL)));
        db.close();
        return user;
    }

    // 转换评论事件显示格式
    private String TimeTranslate(String source){
        // 将字符串解析为 Date 对象
        Date date = null;
        try {
            date = Util.sdf.parse(source);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        Date currentDate = new Date();
        // 计算时间差（单位：毫秒）
        long diffInMilliseconds =  currentDate.getTime() - date.getTime();
        long diffInMinutes = diffInMilliseconds / (60 * 1000);
        long diffInHours = diffInMinutes / 60;
        long diffInDays = diffInHours / 24;
        if (diffInDays >= 1) {       //一天后
            if (diffInDays >= 30) {
                String beijingTime = Util.sdf.format(date);
                return  beijingTime;
            }
            else {
                return diffInDays + "天前";
            }
        }
        else if(diffInHours >= 1){  //一天内
            return  diffInHours + "小时前";
        }
        else{                       //一小时内
            return diffInMinutes + "分钟前";
        }
    }

    @SuppressLint("Range")
    private void CommentInit(){
        // 查询数据库中评论总数
        String countQuery = "SELECT COUNT(*) FROM " + DB_Common_Contract.CommentEntry.TABLE_NAME;
        SQLiteDatabase db_count = dbHelper.getReadableDatabase();
        Cursor cursor_count = db_count.rawQuery(countQuery, null);
        if (cursor_count.moveToFirst()) {
            comment_num = cursor_count.getInt(0);
        }
        TextView show_commentNUM = findViewById(R.id.tv_comment_num);
        show_commentNUM.setText( comment_num + "条评论");
        cursor_count.close();
        // 按点赞数排序评论
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor_comment = dbHelper.QueryDB(query_comment, db);

        if (cursor_comment != null && cursor_comment.moveToFirst()) {
            int commentIndex = 1;
            do {
                data.add(new Comment(commentIndex - 1,cursor_comment));
                comment_id.add( cursor_comment.getString(cursor_comment.getColumnIndex(DB_Common_Contract.CommentEntry._ID)));
                //切换到下一个评论
                commentIndex++;
                // 检查是否达到指定的操作次数
                if (commentIndex > comment_num || commentIndex > 9) {
                    break; // 跳出循环
                }
            } while (cursor_comment.moveToNext());
        }
        else {
            //显示没有评论（新建一个，修改是否可见）
        }
        db.close();
    }

    private void addButtonClickListener(){
        // 发送评论部分
        Button button_sent;
        EditText et_comment = findViewById(R.id.et_sent_comment);
        button_sent = findViewById(R.id.bt_sent_comment);
        button_sent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (!et_comment.getText().toString().equals("")) {
                    dbHelper.addComment(et_comment.getText().toString());
                }
                // 发送之后更新内容
            }
        });
        // 退出部分
        ImageButton button_exit;
        button_exit = findViewById(R.id.bt_exit);
        button_exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //动画
                finish();
            }
        });
    }

    public class Comment{
        private String id = "";
        private String support = "";
        private String content = "";
        private String time = "";
        private String avatarURL = "";
        private String userName = "";

        public Comment(){}

        @SuppressLint("Range")
        public Comment(int index, Cursor cursor_comment){
            // 报错信息
            if (index < 0 || index > comment_num) return;

            if (cursor_comment != null && cursor_comment.moveToFirst()) {
                cursor_comment.moveToPosition(index);
                id = cursor_comment.getString(cursor_comment.getColumnIndex(DB_Common_Contract.CommentEntry._ID));
                content = cursor_comment.getString(cursor_comment.getColumnIndex(DB_Common_Contract.CommentEntry.COLUMN_COMMENT_TEXT));
                time = TimeTranslate(cursor_comment.getString(cursor_comment.getColumnIndex(DB_Common_Contract.CommentEntry.COLUMN_COMMENT_TIME)));
                support = cursor_comment.getString(cursor_comment.getColumnIndex(DB_Common_Contract.CommentEntry.COLUMN_COMMENT_SUPPORT));

                User user = GetUserDataFromID(cursor_comment.getString(cursor_comment.getColumnIndex(DB_Common_Contract.CommentEntry.COLUMN_COMMENT_UserID)));
                userName = user.name;
                avatarURL = user.avatarURL;

            }
        }
        public String getId(){ return id;}

        public String getUserName() { return userName;}

        public String getContent() { return content;}

        public String getTime() { return time;}

        public String getAvatarURL() { return avatarURL;}

        public String getSupport() { return support;}
    }

}
